package com.qf.future;

import com.utils.ExecutorUtils;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 组合任务
 */
public class Demo03 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ThreadPoolExecutor pool = ExecutorUtils.getExcutorsPool();

        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " future1 开始执行。。");
            return 10;
        }, pool);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " future2 开始执行。。");
            return 20;
        }, pool);


        // 组合两个任务,不需要两个任务的返回值
//        future2.runAfterBothAsync(future1, () -> {
//            System.out.println(Thread.currentThread().getName() + " 任务1和任务2执行完成了");
//        }, pool);

//        // 组合两个任务，需要前面任务的返回结果
//        future2.thenAcceptBothAsync(future1, (f2, f1) -> {
//            System.out.println(Thread.currentThread().getName() + " 任务1和任务2执行完成了,f1:" + f1 + ",f2:" + f2);
//        }, pool);


        // 组合两个任务，需要前面任务的返回结果,并结算
        CompletableFuture<Integer> future = future2.thenCombineAsync(future1, (f2, f1) -> {
            System.out.println(Thread.currentThread().getName() + " 任务1和任务2执行完成了,f1:" + f1 + ",f2:" + f2);
            return f2 + f1;
        }, pool);

        System.out.println(Thread.currentThread().getName() + " sum:" +future.get());
        pool.shutdown();

    }
}
